package part18;

import java.io.*;
import java.util.Random;

/**
 * @author wcj
 * @Date 2021/6/4 17:29
 * @Version 1.0
 */
public class Part1832 implements Serializable {
    private static Random random = new Random(47);

    private Data[] d = {
            new Data(random.nextInt(1)),
            new Data(random.nextInt(1)),
            new Data(random.nextInt(1))
    };

    private Part1832 next;
    private char c;

    public Part1832(int i, char x) {
        System.out.println("Part1832 constructor:" + i);
        this.c = x;
        if (--i > 0) {
            this.next = new Part1832(i, (char) (x + 1));
        }
    }

    public Part1832() {
        System.out.println("Default Constructor");
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append(c);
        res.append("(");
        for (Data data : d) {
            res.append(data);
        }
        res.append(")");
        if (next != null) {
            res.append(next);
        }
        return res.toString();
    }

    /**
     * 对象序列化机制：即实现Serializable接口
     * 序列化即将对象转换为一个字节序列，可以通过网络等进行传输，并且通过其字节序列我们可以完整的恢复这个对象
     * 之所以有对象序列化是因为Java中的远程方法调用，使用序列化可以让远程网络传输的对象看起来像是在本机的程序中一样
     * 另外实现java beans的后期恢复
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Part1832 a = new Part1832(6, 'a');
        System.out.println("a = " + a);

        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("part1832.out"));
        out.writeObject("Part1832 strong\n");
        out.writeObject(a);
        out.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream("part1832.out"));
        String s = (String) in.readObject();
        Part1832 part1832 = (Part1832) in.readObject();
        System.out.println("s = " + s + "Part1832:" + part1832);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out2 = new ObjectOutputStream(bout);
        out2.writeObject("Part1832 strong\n");
        out2.writeObject(a);
        out2.flush();

        ObjectInputStream bin = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
        String s1 = (String) bin.readObject();
        Part1832 part18321 = (Part1832) bin.readObject();
        System.out.println("s = " + s1 + "Part1832:" + part18321);
    }
}

class Data implements Serializable {

    private int n;

    public Data(int n) {
        this.n = n;
    }

    @Override
    public String toString() {
        return Integer.toString(n);
    }
}


